package lhb.test.SC.oauth2.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
	
	@Autowired
    private TokenStore tokenStore;

    /**
     * 跳转登录页面
     * @param error
     * @param model
     * @return
     */
    @RequestMapping(value = "/login")
    public String login(String error,ModelMap model){
        model.addAttribute("error",error);
        return "login";
    }

    /**
     * 退出登录
     * @param request
     */
    @RequestMapping(value = "/logout")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody String logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String tokenValue = authHeader.replace("Bearer", "").trim();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            tokenStore.removeAccessToken(accessToken);
        }
        return "SUCCESS";
    }
}
